let express = require('express');
let router = express.Router();
let fs = require('fs');
// 初始化Client
let co = require('co');
let OSS = require('ali-oss');
let client = new OSS({
  region: 'oss-cn-wulanchabu',
  accessKeyId: 'LTAI5tK2nKMoX6XRzLdPe6p8',
  accessKeySecret: 'qfsODryv7Wml5uDvYlxwWViS3PNXrk'
});

let ali_oss = {
    bucket: 'restaurant-imgs',
    endPoint: 'oss-cn-wulanchabu.aliyuncs.com',
}
// 微信小程序 图片上传
let multer  = require('multer')
let upload = multer({ dest: './tmp/' })
// 图片上传
router.all('/upload2', upload.single('file'), function(req, res, next){
  // 跨域的代码
  res.header("Access-Control-Allow-Origin", req.headers.origin);
  res.writeHead(200,{'Content-Type':'text/plain;charset=utf-8'})
    // 文件路径
    let filePath = './' + req.file.path;  
    // 文件类型
    let temp = req.file.originalname.split('.');
    let fileType = temp[temp.length - 1];
    let lastName = '.' + fileType;
    // 构建图片名
    let fileName = Date.now() + lastName;
    // 图片重命名
    fs.rename(filePath, fileName, (err) => {
        if (err) {
            res.end(JSON.stringify({status:'102',msg:'文件写入失败'}));
            return; 
        }else{
            
            let localFile = './' + fileName;  
            let key = fileName;

            // 阿里云 上传文件 
            co(function* () {
              client.useBucket(ali_oss.bucket);
              let result = yield client.put(key, localFile);
              let imageSrc = 'http://restaurant-imgs.oss-cn-wulanchabu.aliyuncs.com/' + result.name;
              // 上传之后删除本地文件
              fs.unlinkSync(localFile);
              
              res.end(JSON.stringify({status:'100',msg:'上传成功',imageUrl:imageSrc})); 
           
              return 
            }).catch(function (err) {
              // 上传之后删除本地文件
              fs.unlinkSync(localFile);
              res.end(JSON.stringify({status:'101',msg:'上传失败',error:JSON.stringify(err)})); 
              return 
          
            });
        }
    });
})
module.exports = router;